
new Vue({
  el: '#z_head',
  data: {
    navList: [],
    key: '',
    url: window.location.href.split('/').pop(),
    index: -1,
    userObj: localStorage.getItem('userObj') && localStorage.getItem('isLogin') ? JSON.parse(localStorage.getItem('userObj')) : null,

    lastLogin: localStorage.getItem('userObj') && localStorage.getItem('isLogin') ? JSON.parse(localStorage.getItem('userObj')).lastLogin : null,

    clientInfo: {},
    innerIp: '',
    oldOnline: '',
    socket: null,
    fromMessageName: '',
    messageNotice: { state: 1, num: 0 },
  },
  methods: {
    online() {
      this.noReadMessage();
      var new_element = document.createElement("script");
      new_element.setAttribute("src", "https://cdn.bootcss.com/socket.io/2.2.0/socket.io.js");
      document.body.appendChild(new_element);
      setTimeout(() => {
        let socket = io.connect('http://localhost/');
        this.socket = socket;
        var user = {};
        user.clientIp = this.clientInfo.cip;
        user.innerIp = this.innerIp;
        user.name = this.userObj.name;
        user._id = this.userObj._id;
        user.pageTitle = document.title;
        socket.on('connect', () => {
          socket.emit('login', user);
          this.oldOnline = '在线';
        })
        socket.on('online', (data) => {
          if (data.online == '离线') return false;
          this.userObj = JSON.parse(localStorage.getItem('userObj'));
          //this.oldOnline = this.userObj.online;
          this.userObj.online = data.online;
          localStorage.setItem('userObj', JSON.stringify(this.userObj))
        });
        socket.on('receiveNotice', (data) => {
          var that = this;
          if ($('.messageRight .messageTitle') && data.des.indexOf('线') != -1) {
            $('.messageRight .messageTitle').click();
          }
          if (data.des.indexOf('发来') != -1) {
            this.fromMessageName = data.name;
            this.messageNotice.state = 0;
            this.messageNotice.num += 1;
            if ($('.onlineListItem')) {
              $('.onlineListItem').each(function () {
                if ($(this).attr('data-on')==1) {
                  $(this).click();
                  setTimeout(() => {
                    if ($('#scorllChat')) {
                      $('#scorllChat').scrollTop($('#scorllChat').prop('scrollHeight'));
                    }
                    //Head.$emit('noReadMessage',1);
                  }, 300);
                  setTimeout(()=>{that.noReadMessage()},200);
                }
              })
            }
          }
          noticeDiv(data.des, data.state, 2000);
        });
      }, 400);
    },
    getInnerIp() {
      var RTCPeerConnection = window.RTCPeerConnection || window.webkitRTCPeerConnection || window.mozRTCPeerConnection;
      if (RTCPeerConnection) (() => {
        var rtc = new RTCPeerConnection({ iceServers: [] });
        if (1 || window.mozRTCPeerConnection) {
          rtc.createDataChannel('', { reliable: false });
        };

        rtc.onicecandidate = (evt) => {
          if (evt.candidate) grepSDP("a=" + evt.candidate.candidate);
        };
        rtc.createOffer((offerDesc) => {
          grepSDP(offerDesc.sdp);
          rtc.setLocalDescription(offerDesc);
        }, (e) => { console.warn("offer failed", e); });


        var addrs = Object.create(null);
        addrs["0.0.0.0"] = false;
        updateDisplay = (newAddr) => {
          if (newAddr in addrs) return;
          else addrs[newAddr] = true;
          var displayAddrs = Object.keys(addrs).filter((k) => { return addrs[k]; });
          this.innerIp = displayAddrs[0];


        }

        grepSDP = (sdp) => {
          var hosts = [];
          sdp.split('\r\n').forEach((line) => {
            if (~line.indexOf("a=candidate")) {
              var parts = line.split(' '),
                addr = parts[4],
                type = parts[7];
              if (type === 'host') updateDisplay(addr);
            } else if (~line.indexOf("c=")) {
              var parts = line.split(' '),
                addr = parts[2];
              updateDisplay(addr);
            }
          });
        }
      })(); else { }
    },
    checkUser() {
      if (this.userObj) {
        this.online();
        var new_element = document.createElement("script");
        new_element.setAttribute("src", "http://pv.sohu.com/cityjson");
        document.body.appendChild(new_element);
        setTimeout(() => { this.clientInfo = returnCitySN; this.getInnerIp() }, 300);
        setTimeout(() => { this.loginInit() }, 1000);
        return $('#z_head .searchInputArea').before(`
        <a class="user" href="javascript:;">
          <span class="userImg" :style="'background-image:url('+ userObj.imgSrc +')'" title="个人中心" @click="toUserInfo"></span>
          <span class="userName" title="个人中心" @click="toUserInfo">{{userObj.name}}</span>
          <span class="logOut" @click="logOut" title="退出">退出</span>  
        </a>
        `)
      } else {
        $('#z_head .searchInputArea').before(`
        <a class="loginUrl" href="javascript:;">
            <span @click="toLogin">登录</span>
            <span @click="toRegister">注册</span>
        </a>
        `)
        if (this.url == 'login' || this.url == 'register') return false;
        noticeDiv('你还没有登录呢', 'error', 2000, function () { window.location.href = '/login'; });

      }
    },
    readFile() {
      this.$http.get('./public/source/data.json').then(response => {
        let res = response.body;
        if (res) {
          this.navList = res.navs;
          if (!this.url) return this.index = 0;
          res.navs.filter((item, index) => {
            if (this.url.indexOf(item.url.split('/').pop()) != -1 && index != 0) return this.index = index;
          })
        }
      }, response => {
        console.log('请求数据失败！');
      });
    },
    readIndex() {
      if (this.index < 0) return false;
      this.navList[this.index].check = true;
    },
    noReadMessage() {
      this.$http.post('/moongoDB/getMessage', {
        id: this.userObj._id
      }).then(resp => {
        if (resp) {
          var chatMessage = resp.body.chatMessage;
          var lengthArr = [];
          this.messageNotice.state = 1;
          chatMessage.map(chat => {
            chat.history.map(message => {
              if (message.msgType == 0 && message.read == 0) {
                this.messageNotice.state = 0;
                lengthArr.length += 1;
              }
            })
          })
          this.messageNotice.num = lengthArr.length;
        }
      })
    },
    toSearch() {
      if (this.key !== '') {
        window.open(`/search?key=${this.key}`, '_blank');
      }
    },
    loginInit() {
      var userObj = this.userObj;
      if (!userObj.clientIp || !userObj.innerIp || this.oldOnline == '离线' || true) { }
      else if (userObj.clientIp != this.clientInfo.cip || userObj.innerIp != this.innerIp)
        return noticeDiv('登录信息已失效', 'error', 2000, function () { localStorage.removeItem('isLogin'); window.location.href = '/login'; });

      var date = new Date();
      var time = `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()} ${addZero(date.getHours())}:${addZero(date.getMinutes())}:${addZero(date.getSeconds())}`;
      var _id = userObj._id;
      var clientIp = this.clientInfo.cip;
      var address = this.clientInfo.cname;
      var innerIp = this.innerIp;
      this.$http.post('/moongoDB/loginInit', {
        _id: _id,
        lastLogin: time,
        clientIp: clientIp,
        address: address,
        innerIp: innerIp,
      }).then(resp => {
        if (resp.body != '') {
          noticeDiv(resp.body.text, 'info', 2000);
          userObj.exp = resp.body.exp;
        }
        userObj.lastLogin = time;
        localStorage.setItem('userObj', JSON.stringify(userObj))
      })
    },
    logOut() {
      if (!this.userObj.checkAgree) localStorage.removeItem('userObj');
      localStorage.removeItem('isLogin');
      this.socket.emit('disconnect');
      noticeDiv('退出成功，请重新登录哦', 'success', 2000, function () { window.location.href = '/login'; });
    },
    toLogin() {
      window.location.href = "/login";
    },
    toRegister() {
      window.location.href = "/register";
    },
    toUserInfo() {
      if (this.url == 'userInfo') return false;
      window.open('/userInfo', '_blank');
    }
  },

  created() {
    this.readFile();
    this.checkUser();

    $("#headUl").html(`
    <a :href="item.url" v-for="(item,index) in navList" :key="item.title" :target="url==''?'_blank':''">
       <li :class="item.check ? 'active': ''">{{ item.title }}</li>
    </a>`);
    $("#headUl").next('.user').children('.userImg').html('<span v-if="messageNotice.state==0" class="messageNotice" >{{messageNotice.num}}</span>');
  },
  mounted() {
    if($('.info_menu li')){
      setInterval(()=>this.noReadMessage(),5000);
    }
  },
  updated() {
    this.readIndex();
  }

});
